/***************
 * Directory Tree Panel
 */
AIR2.Directory.Tree = function() {
    /* template to format a single organization (at any level) */
    AIR2.Directory.Tree.orgTpl = new Ext.XTemplate(
        '<div class="org">' +
          '<div class="info">' +
            '<span class="trigger air2-icon-arrow {[this.getArrowCls(values)]}">' +
              '<span class="name-short">{[AIR2.Format.orgName(values)]}</span>' +
            '</span>' +
            '<span>' +
              ' - {[AIR2.Format.orgNameLong(values, true)]} ({user_count})' +
            '</span>' +
          '</div>' +
          '<div class="children" isloaded="{[this.isLoadedCls(values)]}" parent="{org_uuid}">' +
            '{[this.formatChildren(values)]}' +
            '{[this.formatUsers(values)]}' +
          '</div>' +
        '</div>',
        {
            isLoadedCls: function(orgObj) {
                // "children"/"UserOrg" won't exist if a level isn't expanded
                return (orgObj.children || orgObj.UserOrg) ? true : false;
            },
            getArrowCls: function(orgObj) {
                var c = (orgObj.children || orgObj.UserOrg);
                return (c) ? 'air2-icon-arrow-open' : 'air2-icon-arrow-closed';
            },
            formatChildren: function(orgObj) {
                var str = '';
                if (orgObj.children) {
                    for (var i=0; i<orgObj.children.length; i++) {
                        str += AIR2.Directory.Tree.orgTpl.apply(orgObj.children[i]);
                    }
                }
                return str;
            },
            formatUsers: function(orgObj) {
                var str = '';
                if (orgObj.UserOrg) {
                    for (var i=0; i<orgObj.UserOrg.length; i++) {
                        if (i % 2 == 0) orgObj.UserOrg[i].rowcls = 'rowalt';
                    }

                    if (orgObj.UserOrg.length == 0) {
                        str += '<div class="nousers">No Users</div>';
                    }
                    else {
                        str += AIR2.Directory.Tree.userTpl.apply(orgObj.UserOrg);
                    }
                }
                return str;
            }
        }
    );
    AIR2.Directory.Tree.orgTpl.compile();

    /* template to format Users within an organization */
    AIR2.Directory.Tree.userTpl = new Ext.XTemplate(
        '<table><tpl for=".">' +
          '<tr class="user {rowcls}">' +
            '<td class="col1">{[AIR2.Format.userName(values.User, true)]}</td>' +
            '<td class="col2">{[values.AdminRole.ar_name]}</td>' +
            '<td class="col3">{[AIR2.Format.userPhone(values.User, true)]}</td>' +
            '<td class="col4">{[AIR2.Format.userEmail(values.User, true)]}</td>' +
          '</tr>' +
        '</tpl></table>'
    );
    AIR2.Directory.Tree.userTpl.compile();

    /* visually expand (animate) an organization */
    AIR2.Directory.Tree.openOrg = function(htmlEl) {
        var el = Ext.get(htmlEl);
        var t = el.first('.children');
        var l = t.getAttribute('isloaded'), u = t.getAttribute('parent');

        if (!l || l == 'false') {
            t.update('<div class="child-load-mask">Loading...</div>');
            AIR2.Directory.Tree.loadOrg(u, htmlEl);
        }

        t.slideIn('t', {useDisplay: true, duration: .15});
        el.child('.trigger').replaceClass('air2-icon-arrow-closed', 'air2-icon-arrow-open');
    };

    /* visually close (animate) an organization */
    AIR2.Directory.Tree.closeOrg = function(orgEl) {
        if (!orgEl.first) orgEl = Ext.get(orgEl);
        var t = orgEl.first('.children');
        t.slideOut('t', {useDisplay: true, duration: .15});
        orgEl.child('.air2-icon-arrow').replaceClass('air2-icon-arrow-open', 'air2-icon-arrow-closed');
    };

    /* ajax-load the contents/children of an organization */
    AIR2.Directory.Tree.loadOrg = function(uuid, htmlEl) {
        Ext.Ajax.request({
            method: 'GET',
            url: AIR2.HOMEURL + '/directory.json',
            params: {org_uuid: uuid},
            callback: function(opts, success, resp) {
                if (success) {
                    var data = Ext.util.JSON.decode(resp.responseText);
                    AIR2.Directory.Tree.orgTpl.overwrite(htmlEl, data.radix);
                }
                else {
                    Logger("UNSUCCESS!");
                }
            }
        });
    };

    /* return the actual panel */
    var p = new AIR2.UI.Panel({
        cls: 'air2-directory-panel',
        colspan: 2,
        rowspan: 3,
        title: 'Directory',
        iconCls: 'air2-icon-directory',
        tools: ['->', {
            xtype: 'air2textfilter',
            emptyText: 'Filter Users',
            listeners: {
                filterchange: function(fld, value) {
                    if (value.length > 0) {
                        p.store.setBaseParam('all', 1);
                        p.store.setBaseParam('user', value);
                    }
                    else {
                        delete p.store.baseParams.all;
                        delete p.store.baseParams.user;
                    }
                    p.store.load();
                }
            }
        },'  ',{
            xtype: 'air2button',
            air2type: 'BLUE',
            text: 'Expand',
            handler: function(btn) {
                if (btn.usrhidden) {
                    delete p.store.baseParams.all;
                    delete p.store.baseParams.user;
                    btn.usrhidden = false;
                    btn.setText('Show All');
                }
                else {
                    p.store.setBaseParam('all', 1);
                    p.store.setBaseParam('user', 0);
                    btn.usrhidden = true;
                    btn.setText('Collapse');
                }
                p.store.load();
            }
        }],
        storeData: AIR2.Directory.DATA,
        url: AIR2.HOMEURL + '/directory',
        tpl: new Ext.XTemplate(
            '<table class="header"><tr>' +
              '<td class="col1">Contact</td>' +
              '<td class="col2">Title</td>' +
              '<td class="col3">Phone</td>' +
              '<td class="col4">Email</td>' +
            '</tr></table>' +
            '<tpl for=".">' +
              '{[AIR2.Directory.Tree.orgTpl.apply(values)]}' +
            '</tpl>'
        ),
        listeners: {
            afterrender: function(comp) {
                comp.el.on('click', function(e) {
                    if (e.getTarget('.trigger.air2-icon-arrow-open')) {
                        AIR2.Directory.Tree.closeOrg(e.getTarget('.org'));
                    }
                    else if (e.getTarget('.trigger.air2-icon-arrow-closed')) {
                        AIR2.Directory.Tree.openOrg(e.getTarget('.org'));
                    }
                });
            }
        }
    });
    return p;
}